package com.namo.cchadmin.service.impl;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.namo.cchadmin.consumer.CaptchaConsumer;
import com.namo.cchadmin.dao.AdminMapper;
import com.namo.cchadmin.entity.Admin;
import com.namo.cchadmin.service.AdminService;
import com.namo.cchcommon.api.ResultCode;
import com.namo.cchcommon.exception.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author WangXin
 * @date 2021/5/17 20:07
 */
@Service
@Slf4j
public class AdminServiceImpl implements AdminService {
    @Autowired
    CaptchaConsumer captchaConsumer;
    @Autowired
    AdminMapper adminMapper;

    @Autowired
    Gson gson;
    @Override
    public Admin login(String username, String password, String captchaId, String captchaCode) {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("id",captchaId);
        jsonObject.addProperty("input_code",captchaCode);
        String res = captchaConsumer.checkCaptcha(gson.toJson(jsonObject));
        JsonObject resJson = gson.fromJson(res, JsonObject.class);
        if(resJson.get("code").getAsInt() != ResultCode.SUCCESS.getCode()){
                log.error("验证码验证错误==>"+resJson);
                throw new ApiException(500L,resJson.get("message").getAsString());
        }
        List<Admin> admins = adminMapper.selectByUsernameAndPassword(username, password);
        if (admins.size()!=1){
            throw new ApiException(500L,"用户名或密码错误");
        }
        return admins.get(0);
    }
}
